﻿using System;
using System.Web.Mvc;
using Kooboo.Commerce.Contexts.ShopSettings;


namespace Kooboo.Web.Areas.Commerce.Controllers
{
    
    
    using Kooboo.Web.Mvc;
    using Kooboo.Commerce;
    [Authorize(Roles = "Administrator")]
    public class SettingsController : ManagementController
    {
        #region Index

        [HttpGet]
        public ActionResult Index()
        {
            
            var shopSetting = this.Actor.GetShopSettings();
            shopSetting.ThreadCulture = shopSetting.ThreadCulture == null ? "" : shopSetting.ThreadCulture.Trim();



            ViewData["CultureInfos"] = CultureHelper.BuildCultures(shopSetting.ThreadCulture);

            ViewData["Currencies"] = CurrencyHelper.BuildCurrencies(shopSetting.CurrencyISOCode);

            ViewData["settings_validators"] = ModelClientMetadataBuilder
                .BuildFor<IShopSetting>(this.Url.Action<SettingsController>(i => i.Index()))
                .ValidateFor(i => i.CurrencyISOCode)
                .ValidateFor(i => i.DefaultDeliveryDays)
                .ValidateFor(i => i.PriceIndex)
                .ValidateFor(i => i.SizeUnit)
                .ValidateFor(i => i.ThreadCulture)
                .ValidateFor(i => i.WeightUnit)
                .ToMetadata();

            ViewData["imagesize_validators"] = ModelClientMetadataBuilder
                .BuildFor<IImageSize>("","imageSize")
                .ValidateFor(i => i.Height)
                .ValidateFor(i => i.Name)
                .ValidateFor(i => i.Width)
                .ToMetadata();
                

            return View(shopSetting);
        }


        [HttpPost]
        public ActionResult Index(IShopSetting settings)
        {
        
            if (ModelState.IsValid)
            {
                try
                {
                    this.Actor.Put(settings);
                    return Json(true);
                }
                catch (Exception ex)
                {
                    return Json(new { Error = ex.Message });
                }
            }
            else
            {
                return Json(new { Message = ModelState.GetErrorMessages() });
            }
        }


        #endregion
    }
}
